<template>
  <div class="account-bill-list">
    <a-card title="账单管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="标题">
            <a-input v-model:value="searchForm.title" placeholder="请输入账单标题" />
          </a-form-item>
          <a-form-item label="类型">
            <a-select v-model:value="searchForm.type" placeholder="请选择类型" style="width: 120px">
              <a-select-option :value="''">全部</a-select-option>
              <a-select-option :value="1">收入</a-select-option>
              <a-select-option :value="2">支出</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
              <a-select-option :value="''">全部</a-select-option>
              <a-select-option :value="0">草稿</a-select-option>
              <a-select-option :value="1">已确认</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-area">
        <a-button type="primary" @click="handleAdd">
          <plus-outlined />
          新增账单
        </a-button>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="billList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === 1 ? 'green' : 'red'">
              {{ record.type === 1 ? '收入' : '支出' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'blue' : 'default'">
              {{ record.status === 1 ? '已确认' : '草稿' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
              <a-popconfirm
                title="确定要删除这个账单吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 账单表单模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="标题" name="title">
              <a-input v-model:value="form.title" placeholder="请输入账单标题" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="金额" name="amount">
              <a-input-number v-model:value="form.amount" :min="0" style="width:100%" placeholder="请输入金额" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="类型" name="type">
              <a-select v-model:value="form.type" placeholder="请选择类型">
                <a-select-option :value="1">收入</a-select-option>
                <a-select-option :value="2">支出</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="form.status" placeholder="请选择状态">
                <a-select-option :value="0">草稿</a-select-option>
                <a-select-option :value="1">已确认</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="支付方式" name="paymentMethod">
              <a-select v-model:value="form.paymentMethod" placeholder="请选择支付方式">
                <a-select-option :value="1">现金</a-select-option>
                <a-select-option :value="2">银行卡</a-select-option>
                <a-select-option :value="3">支付宝</a-select-option>
                <a-select-option :value="4">微信</a-select-option>
                <a-select-option :value="5">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="日期" name="billDate">
              <a-date-picker v-model:value="form.billDate" style="width:100%" show-time format="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="标签" name="tags">
              <a-input v-model:value="form.tags" placeholder="多个标签用逗号分隔" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分类ID" name="categoryId">
              <a-input v-model:value="form.categoryId" placeholder="请输入分类ID" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入描述" :rows="2" />
        </a-form-item>
        <a-form-item label="附件" name="attachments">
          <a-input v-model:value="form.attachments" placeholder="请输入附件路径（多个用逗号分隔）" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import {
  getAccountBillPage,
  addAccountBill,
  editAccountBill,
  deleteAccountBill,
  getAccountBillById
} from '@/api/accountBill'

const loading = ref(false)
const billList = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增账单')
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  status: ''
})

// 账单表单
const form = reactive({
  id: '',
  title: '',
  amount: null,
  type: 1,
  status: 0,
  paymentMethod: 1,
  billDate: '',
  tags: '',
  categoryId: '',
  description: '',
  attachments: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '标题', dataIndex: 'title', key: 'title' },
  { title: '金额', dataIndex: 'amount', key: 'amount' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '支付方式', dataIndex: 'paymentMethod', key: 'paymentMethod' },
  { title: '日期', dataIndex: 'billDate', key: 'billDate' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action', width: 180 }
]

// 校验规则
const rules = {
  title: [{ required: true, message: '请输入账单标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  billDate: [{ required: true, message: '请选择日期', trigger: 'change' }]
}

// 查询账单分页数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }
    const res = await getAccountBillPage(params)
    if (res.code === 0) {
      billList.value = res.data.records || []
      pagination.total = res.data.total || 0
    }
  } finally {
    loading.value = false
  }
}

onMounted(fetchData)

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}
const handleReset = () => {
  searchForm.title = ''
  searchForm.type = ''
  searchForm.status = ''
  pagination.current = 1
  fetchData()
}
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}
const handleAdd = () => {
  modalTitle.value = '新增账单'
  Object.assign(form, {
    id: '',
    title: '',
    amount: null,
    type: 1,
    status: 0,
    paymentMethod: 1,
    billDate: '',
    tags: '',
    categoryId: '',
    description: '',
    attachments: ''
  })
  modalVisible.value = true
}
const handleEdit = async (record) => {
  modalTitle.value = '编辑账单'
  const res = await getAccountBillById(record.id)
  if (res.code === 0) {
    Object.assign(form, res.data)
    modalVisible.value = true
  }
}
const handleView = async (record) => {
  const res = await getAccountBillById(record.id)
  if (res.code === 0) {
    message.info(JSON.stringify(res.data, null, 2))
  }
}
const handleDelete = async (record) => {
  const res = await deleteAccountBill(record.id)
  if (res.data && res.data.code === 200) {
    message.success('删除成功')
    fetchData()
  } else {
    message.error(res.data?.message || '删除失败')
  }
}
const handleModalOk = async () => {
  await formRef.value.validate()
  let res
  if (!form.id) {
    // 新增
    res = await addAccountBill(form)
    if (res.data && res.data.code === 200) {
      message.success('新增成功')
      modalVisible.value = false
      fetchData()
    } else {
      message.error(res.data?.message || '新增失败')
    }
  } else {
    // 编辑
    res = await editAccountBill(form)
    if (res.data && res.data.code === 200) {
      message.success('编辑成功')
      modalVisible.value = false
      fetchData()
    } else {
      message.error(res.data?.message || '编辑失败')
    }
  }
}
const handleModalCancel = () => {
  modalVisible.value = false
}
</script>

<style scoped>
.account-bill-list {
  padding: 24px;
}
.action-area {
  margin-bottom: 16px;
}
@media (max-width: 600px) {
  .account-bill-list { padding: 4px !important; }
  .action-area { margin-bottom: 8px !important; }
  .ant-table { font-size: 12px !important; overflow-x: auto !important; min-width: 480px; }
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td { padding: 4px 6px !important; }
  .ant-modal { width: 96vw !important; max-width: 96vw !important; min-width: 0 !important; }
}
</style>
